package com.neurotech.pcc.ui

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import androidx.navigation.fragment.NavHostFragment
import com.neurotech.pcc.R
import com.neurotech.pcc.dummy.AreaDevice
import com.neurotech.pcc.dummy.AreaDeviceScanListener
import com.neurotech.pcc.other.NetworkUtils
import com.neurotech.pcc.other.liteStatusBarIcon
import com.neurotech.pcc.other.pop
import com.neurotech.pcc.ui.adapter.ScanItemAdapter
import kotlinx.android.synthetic.main.fragment_scan.*

/**
 * A fragment representing a list of scan Items.
 */
class ScanFragment : Fragment() {

    private lateinit var scanItemAdapter: ScanItemAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_scan, container, false)
        scanItemAdapter = ScanItemAdapter()
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (activity!! as MainActivity).setSupportActionBar(toolbar)
        (activity!! as MainActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
        swipeRefreshLayout?.isRefreshing = true
        swipeRefreshLayout?.postDelayed({
            swipeRefreshLayout?.isRefreshing = false
        }, 500)
        swipeRefreshLayout?.setOnRefreshListener {
            swipeRefreshLayout?.postDelayed({
                start()
                swipeRefreshLayout?.isRefreshing = false
            }, 500)
        }
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.adapter = scanItemAdapter
        start()
    }

    fun start() {
        scanItemAdapter.clear()
        NetworkUtils.scan(object : AreaDeviceScanListener {
            override fun onScan(areaDevice: AreaDevice) {
                scanItemAdapter.add(areaDevice)
            }
        })
    }

    override fun onResume() {
        super.onResume()
        liteStatusBarIcon(activity?.window?.decorView)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == android.R.id.home) {
            pop()
        }
        if (item?.itemId == R.id.menu_add) {
            NavHostFragment.findNavController(this).navigate(R.id.action_scanFragment_to_configFragment)
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater!!.inflate(R.menu.menu_add, menu)
    }
}
